//
//  UserDepositVC.m
//  huien
//
//  Created by yiban on 2018/2/28.
//  Copyright © 2018年 lcb. All rights reserved.
//

#import "UserDepositVC.h"
#import <WebKit/WebKit.h>
@interface UserDepositVC ()<WKUIDelegate,WKScriptMessageHandler,LcbLoginDelegate>
{
    
}
@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;
@property(nonatomic,strong)NSString *currentURLString;
@property(nonatomic,strong)NSString *titleString;
@property (weak) id<LcbLoginDelegate> delegate;
+ (instancetype)newController;
@end

@implementation UserDepositVC
@synthesize currentURLString=_currentURLString;
@synthesize titleString=_titleString;

+ (instancetype)newController
{
    return [super new];
}
+ (instancetype)newWithDelegate:(id<LcbLoginDelegate>)delegate
{
    UserDepositVC *viewController = [UserDepositVC newController];
    
    if (viewController) {
        viewController.delegate = delegate;
    }
    
    return viewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.navigationController.navigationBarHidden=YES;
    self.navTitle = @"开通托管";
    //
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 60, 44);
    backButton.tag =100;
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    //
    self.currentURLString = [NSString stringWithFormat:@"%@%@",[LcbDevice sharedLcbDevice].domain,@"/mobileRegistration/to-bank-registor"];
    [self initWKWebView];
    
    [self initProgressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}
-(void)clickNavEvent:(id)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(userDidCancel)]) {
        [_delegate userDidCancel];
    }
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"resultMessage"];
    //
    SessionModel *sessionModel = [HEShare sessionModel];
    if([self.currentURLString containsString:@"?"])
    {
        if (![self.currentURLString containsString:@"sessionId="]) {
            self.currentURLString= [NSString stringWithFormat: @"%@&sessionId=%@&userId=%ld",self.currentURLString,sessionModel.sessionId,(long)sessionModel.session_user.userId];
        }
    }else{
        if (![self.currentURLString containsString:@"sessionId="]) {
            self.currentURLString= [NSString stringWithFormat: @"%@?sessionId=%@&userId=%ld",self.currentURLString,sessionModel.sessionId,(long)sessionModel.session_user.userId];
        }
        
    }
    NSLog(@"-------%@",self.currentURLString);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.currentURLString URLEncodedString]]];
    [self.webView loadRequest:request];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"resultMessage"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)initWKWebView
{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 10.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, YB_HeaderHeight,SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight) configuration:configuration];
    self.webView.UIDelegate = self;
    [self.webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [self.webView setMultipleTouchEnabled:YES];
    [self.webView setAutoresizesSubviews:YES];
    [self.webView.scrollView setAlwaysBounceVertical:YES];
    [self.view addSubview:self.webView];
    
}

- (void)initProgressView
{
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, YB_HeaderHeight, [[UIScreen mainScreen] bounds].size.width, 2)];
    progressView.tintColor = tabcolor;
    progressView.trackTintColor =linecolor;
    [self.view addSubview:progressView];
    self.progressView = progressView;
}



#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    
    if ([message.name isEqualToString:@"resultMessage"]) {
        NSLog(@"扫一扫");
        LcbBaseModel *baseModel = [[LcbBaseModel alloc] init];
        baseModel.code =[message.body[@"code"] integerValue];
        baseModel.message =message.body[@"message"];
        [[NativeRouter sharedNativeRouter] codeHander:self params:baseModel completion:nil];
    }
}

-(void)userLoginOK:(id)userinfo
{
    
}
-(void)userDidCancel
{
    
}
-(void)userLoginFail
{
    
}
@end
